@section('content')
<div class="am-g m-user">
	<div class="am-u-md-12">
		<div class="m-user-title am-cf">
			<h1>我的账户</h1>
			<!-- 
			<span class="free-tip">订单满500元免运费</span>
			 -->
		</div>
	</div>
	<div class="am-u-md-12">
		<div class="m-user-hd">
			<ul class="am-cf">
				<li><a href="{{URL::to('user/order-list')}}">我的订单</a></li>
				<li><a href="{{URL::to('user/address-list')}}">地址</a></li>
				<li><a href="{{URL::to('user/info')}}">登陆资料</a></li>
				<li><a href="{{URL::to('user/favorite-list')}}">收藏夹</a></li>
			</ul>
		</div>
		<div class="m-user-bd">
			<ul>
				<li>
					<h3>地址</h3>
					<span>添加或修改您的账单地址或送货地址</span>
					<button class='m-btn m-btn-user-add-address' type="button" id="add-address-btn">添加新地址</button>
				</li>
			</ul>
			
			<table class="am-table m-table">
			    <thead>
			        <tr>
			            <th>收件人</th>
			            <th>地址</th>
			            <th>联系电话</th>
			            <th>操作</th>
			        </tr>
			    </thead>
			    <tbody>
			    	@foreach($addresses as $address)
			    	<tr data-id='{{$address->id}}' data-mobile='{{$address->mobile}}' data-name='{{$address->name}}' 
						data-zipcode='{{$address->zipcode}}' data-street='{{$address->street}}'
						data-province_id='{{$address->province_id}}' data-city_id='{{$address->city_id}}' data-district_id='{{$address->district_id}}'>
			            <td>{{$address->name}}</td>
			            <td>{{$address->province.$address->city.$address->district.$address->street.' '.$address->zipcode}}</td>
			            <td>{{$address->mobile}}</td>
			            <td><a href="javascript:void(0)" class='address-update'>修改</a> <a href="javascript:void(0)" class='address-delete'>删除</a></td>
			        </tr>
			    	@endforeach
			    </tbody>
			</table>
		</div>
	</div>
    </div>
</div>

@stop

@section('script')
<script type="text/x-handlebars-template" id="add-address-tpl">
<div class="m-login am-cf">
<h2>添加新地址</h2>
<div class="m-login-bd">
	<div class="m-register">
		<form class="am-form"  id="add-address-form" name="add-address-form" method="post" 
				action="{{URL::to('user/address/add')}}">
			<div class="am-form-group">
		      <label for="name">姓名<span class="m-required">*</span></label>
			  <div class="am-cf m-horizontal-group">
		      <input type="text" class="m-input validate" id="name" name="name" 
				data-rules="required|max_length[32]" data-display="姓名" placeholder="输入姓名">
			  <span class="m-field-error"></span>
              </div>
		    </div>
			<div class="am-form-group">
		      <label for="mobile">手机<span class="m-required">*</span></label>
		      <div class="am-cf m-horizontal-group">
			 <input type="text" class="m-input validate" id="mobile" name="mobile" 
				data-rules="required|mobile" data-display="手机号" placeholder="输入手机号">
			  <span class="m-field-error"></span>
			</div>
		    </div>
			<div class="am-form-group">
		      <label for="zipcode">邮政编码</label>
			  <div class="am-cf m-horizontal-group">
		      <input type="text" class="m-input validate" id="zipcode" name="zipcode" 
				data-rules="max_length[16]|alpha_numeric" data-display=邮政编码" placeholder="输入邮政编码">
			  <span class="m-field-error"></span>
              </div>
		    </div>
			<div class="am-form-group">
		      <label for="province_id">省/直辖市<span class="m-required">*</span></label>
		      <div class="am-cf m-horizontal-group">
			  <select id="province_id" name="province_id" class="m-input validate">
			  </select>
			  <span class="m-field-error"></span>
			 </div>
		    </div>
			<div class="am-form-group">
		      <label for="city_id">市<span class="m-required">*</span></label>
			 <div class="am-cf m-horizontal-group">
			  <select id="city_id" name="city_id" class="m-input validate">
			  </select>
              <span class="m-field-error"></span>
	          </div>
		    </div>
		    <div class="am-form-group">
		      <label for="district_id">区/县<span class="m-required">*</span></label>
			<div class="am-cf m-horizontal-group">
		      <select id="district_id" name="district_id" class="m-input validate">
			  </select>
              <span class="m-field-error"></span>
            </div>
		    </div>
			<div class="am-form-group">
		      <label for="street">详细地址<span class="m-required">*</span></label>
			  <div class="am-cf m-horizontal-group">
   			  <textarea  class="m-input validate" id="street" name="street"
				data-rules="required|max_length[256]" data-display="详细地址" placeholder="请输入详细地址"></textarea>
		      <span class="m-field-error"></span> 
			</div>
		    </div>
			{{Form::token()}}
		    <p><button type="submit" class="m-btn">保存</button></p>
		    <p class="m-form-error"></p>
		</form>
	</div>
</div>
</div>
</script>

<script type="text/x-handlebars-template" id="address-tpl">
<tr data-id='@{{id}}' data-mobile='@{{mobile}}' data-name='@{{name}}' 
	data-zipcode='@{{zipcode}}' data-street='@{{street}}'
	data-province_id='@{{province_id}}' data-city_id='@{{city_id}}' data-district_id='@{{district_id}}'>
	<td>@{{name}}</td>
	<td>@{{province}}@{{city}}@{{district}}@{{street}} @{{zipcode}}</td>
	<td>@{{mobile}}</td>
	<td><a href="javascript:void(0)" class='address-update'>修改</a> <a href="javascript:void(0)" class='address-delete'>删除</a></td>
</tr>
</script>

<script type="text/x-handlebars-template" id="item-tpl">
@{{#each this}}
<option value="@{{id}}" data-id="@{{id}}">@{{name}}</option>
@{{/each}}
</script>
<script type="text/javascript">
$(document).on("click","#add-address-btn",function(){
	$content = $($("#add-address-tpl").html());
	$.dialog.show({
		tpl:$content,
		events:{
			open:function(){
				fillProvinces();
				//增加表单验证
				initAddressForm();
			}
		}
	});
	
});

function initAddressForm(successFn){
	var $form = $("#add-address-form");
	var $submit = $form.find("button");
	var errorFn = function(errors){
		$form.find(".m-field-error").html("");
		if ($.isArray(errors)){
			  $.each(errors,function(i,e){
				  var $msg = $(e.element).next();
				  $msg.text(e.message);
			  });
		  } else {
			  for (var key in errors){
				  var $ele = $form.find("#"+key).next();
				  $ele.text(errors[key][0]);
			  }
		}
	}

	var successFn = successFn || function(data){
		var tpl = $("#address-tpl").text();
		var template = Handlebars.compile(tpl);
		$(".m-table tbody").append(template(data));
		$.dialog.close();
		//默认选中最后一个
	}
	$form.validate(function($form,errors,events){
		errorFn(errors);
	  });
	  var options = {
	            beforeSubmit:function(){
	            	$submit.button('loading');
	            },
	            success: function (data) {
	            	$submit.button('reset');
		            //成功
		            if (data.success){
		            	//刷新当前页面
		            	successFn(data);
		            } else {
		            	errorFn($form,data.errors);
			        }
	            }
	   };
	   $form .ajaxForm(options);
}

function initUpdateAddressForm(data){
	var $form = $("#add-address-form");
	$form.find("#name").val(data["name"]);
	$form.find("#mobile").val(data["mobile"]);
	$form.find("#zipcode").val(data["zipcode"]);
	$form.find("#province_id").val(data["province_id"]);
	$form.find("#city_id").val(data["city_id"]);
	$form.find("#district_id").val(data["district_id"]);
	$form.find("#street").text(data["street"]);
	$form.append("<input name='id' type='hidden' value='"+data.id+"'/>");
}
$(document).on('change','#province_id',function(){
	var $item = $('#province_id').find("option:selected");
	id = $item.data().id;
	$.get("{{URL::to('user/address/cities')}}/"+id,function(data){
		fillCities(data);
	});
});


$(document).on('change','#city_id',function(){
	var $item = $('#city_id').find("option:selected");
	id = $item.data().id;
	$.get("{{URL::to('user/address/districts')}}/"+id,function(data){
		fillDistricts(data);
	});
});

function fillProvinces(pid,cid,successFn){
	var params = "";
	if (pid){
		params = "?pid="+pid+"&cid="+cid;
	}
	$.get("{{URL::to('user/address/provinces')}}"+params,function(data){
		fillSelect($("#province_id"),data['provinces']);
		fillCities(data);
		if (successFn){
			successFn();
		}
	});
}

function fillCities(data){
	fillSelect($("#city_id"),data['cities']);
	fillDistricts(data['districts']);
}

function fillDistricts(data){
	fillSelect($("#district_id"),data);
}

function fillSelect($select,data){
	var tpl = $("#item-tpl").text();
	var template = Handlebars.compile(tpl);
	$select.html(template(data));
}

$(document).on("click",".address-update",function(){
	//
	var $address = $(this).closest("tr").data();
	$content = $($("#add-address-tpl").html());
	$.dialog.show({
		tpl:$content,
		events:{
			open:function(){
				fillProvinces($address.province_id,$address.city_id,function(){
					//初始化修改数据
					initUpdateAddressForm($address);
				});
				//增加表单验证
				initAddressForm(function(data){
					//成功同步数据到dom
					var tpl = $("#address-tpl").text();
					var template = Handlebars.compile(tpl);
					$updateAddress = $(template(data));
					$address = $("tr[data-id='"+data.id+"']");
					$address.data(data);
					$address.html($updateAddress.html());
					$.boxer('close');
				});
			}
		}
	});
	
});

$(document).on("click",".address-delete",function(){
	var $tr = $(this).closest('tr');
	var data = $tr.data();
	var options = {
			content:'确认删除吗？',
			ok:function(){
				
				$.post("{{URL::to('user/address/delete')}}",{id:data.id},function(result){
					if (result.success){
						$tr.remove();
					}
				});
			}
	};
	$.dialog.confirm(options);
});
</script>
@stop
